/**
 * niuniu-server_com.decibel.game.niuniu.bootstrap_IOSession.java
 */
package club.pinea.session;

import club.pinea.proto.BasicProto;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.net.InetSocketAddress;

/**
 * 功能描述:
 *
 * @createTime: 2017年7月28日 下午12:24:34
 * @version: 6.0
 * @updateTime: 2017年7月28日 下午12:24:34
 * @changesSum:
 */
public class IOSession {
    private int sessionId;

    private SessionType type = SessionType.SOCKET;

    ChannelHandlerContext context;

    private String ip;

    public int getSessionId() {
        return sessionId;
    }

    @Override
    public int hashCode() {
        return getSessionId();
    }

    public ChannelHandlerContext getContext() {
        return context;
    }

    public void setContext(ChannelHandlerContext context) {
        this.context = context;
        sessionId = context.hashCode();
        ip = ((InetSocketAddress) context.channel().remoteAddress()).getAddress().getHostAddress();
    }

    public void setType(SessionType type) {
        this.type = type;
    }

    public SessionType getType() {
        return type;
    }

    public String getIp() {
        return ip;
    }

    public void send(BasicProto.BaseMessage msg) {
        if (this.type == SessionType.SOCKET) {
            this.context.writeAndFlush(msg);
        } else if (this.type == SessionType.WEBSOCKET) {
            byte[] bytes = msg.toByteArray();
//			 ByteBuf payload = this.context.alloc().buffer(bytes.length);
//			 payload.writeBytes(bytes);
//			 BinaryWebSocketFrame biy = new BinaryWebSocketFrame(payload);
//	         ChannelFuture fut = this.context.writeAndFlush(biy);

            ByteBuf buf = Unpooled.copiedBuffer(bytes);
            BinaryWebSocketFrame biy = new BinaryWebSocketFrame(buf);
            @SuppressWarnings("unused")
            ChannelFuture fut = this.context.writeAndFlush(biy.copy());
        }
    }

    public void disConnect() {
        if (this.context != null) {
            try {
                this.context.close();
            } catch (Throwable t) {
            }
        }
    }

    public enum SessionType {
        SOCKET, WEBSOCKET
    }
}
